package com.atguigu.gmall.cart.interceptor;

import com.atguigu.gmall.cart.config.JwtProperties;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * @author Jia Fa
 * @create 2021-12-19 18:48
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    // 声明线程的局部变量  独属于某一线程 可避免线程安全问题
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Autowired
    JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*// 调用目标方法之前调用此方法 把userId 或者UserKey
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1l);
        userInfo.setUserKey(UUID.randomUUID().toString());*/
        // 获取登录头信息  设置userKey
        String userKey = CookieUtils.getCookieValue(request, jwtProperties.getUserKey());
        // 客户端第一次访问 如果userKey为空 制作一个放入cookie
        if (userKey == null) {
            userKey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request, response, jwtProperties.getUserKey(), userKey, jwtProperties.getExpire());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserKey(userKey);

        //获取用户的登录信息  设置userId
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        if (StringUtils.isNotBlank(token)){
            // 解析token
            Map<String, Object> map = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            // 从载荷中获取userId
            Long userId = Long.valueOf(map.get("userId").toString());
            userInfo.setUserId(userId);
        }

        // 把信息放入局部变量中供后续服务使用
        THREAD_LOCAL.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 调用删除方法 由于使用的是tomcat线程池, 线程结束后不会回收
        // 线程内部的强引用变量不会被GC回收 逐渐导致OOM
        THREAD_LOCAL.remove();
    }

    /**
     * 封装一个获取线程局部变量值的静态方法
     * @return
     */
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }
}
